<template>
  <div class="DinamicFormItem">
    <el-form-item
      :prop="formItemConfig.propName"
      :label-width="formItemConfig.labelWidth"
      :rules="formItemConfig.rules"
    >
      
      <!-- labelName字段名称 -->
      <template #label>
        <span>{{formItemConfig.labelName}}</span>
      </template>
      <!-- <div
        class="dinamicFormItem-labelName"
        :style="`width:${formItemConfig.labelWidth};display:${
          formItemConfig.type === 'button' ? 'none' : ''
        }`"
        v-if="formItemConfig.labelName"
      >
        <div><label v-if="formItemConfig.isRequired" class="star">*</label>{{ formItemConfig.labelName }}</div>
      </div> -->
      <slot
        v-if="formItemConfig.slotName"
        :name="formItemConfig.slotName"
        :formItem="formItemConfig"
        :form="formValue"
      ></slot>
      <!-- 动态表单组件 -->
      <Suspense v-else>
        <template #default>
          <keep-alive>
            <component
              v-model="formValue"
              :key="formItemConfig.propName"
              :is="getDynamicFormWidget(formItemConfig.type)"
              :attributes="formItemConfig.attributes"
              @notify="handleFormWidgetNotify"
            ></component>
          </keep-alive>
        </template>
        <template #fallback>
          <p>Loading...</p>
        </template>
      </Suspense>
    </el-form-item>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  defineExpose,
  onMounted,
  computed,
  watch,
  defineAsyncComponent
} from "vue";
// import CustomInput from "./Widgets/CustomInput/Index.vue";
// import CustomSelect from "./Widgets/CustomSelect/Index.vue";
// import Button from "./Widgets/Button/Index.vue";

const props = defineProps(["formItemConfig", "modelValue"]);
const emits = defineEmits(["update:modelValue"]);
const formValue = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emits("update:modelValue", value);
  }
});

const dynamicComponents = ref({});
const allComponents = require.context("./Widgets", true, /\.vue$/);
allComponents.keys().forEach((item) => {
  let comp = allComponents(item);
  let name = comp.default.name;
  dynamicComponents.value[name] = comp.default;
});

onMounted(() => {});
// 获取表单组件
function getDynamicFormWidget(type) {
  // 使用已缓存的组件，避免重复加载
  let asyncComp = dynamicComponents.value[type] || null;
  if (!asyncComp) {
    // 如果组件还没有被加载和缓存，则进行加载
    let componentNameKey = Object.keys(dynamicComponents.value).find(
      (x) => x.toLowerCase() === type.toLowerCase()
    );
    if (componentNameKey) {
      let path = dynamicComponents.value[componentNameKey].path;
      asyncComp = defineAsyncComponent(() =>
        import(`@/components/common/DinamicForm/Widgets/${path}.vue`)
      );
      dynamicComponents.value[type] = asyncComp; // 缓存组件
    }
  }
  return asyncComp;
}
// 获取表单组件
function getDynamicFormWidgets(type) {
  // let name = "";
  let componentNameKey = Object.keys(dynamicComponents.value).filter(
    (x) => x === type
  );
  let path = dynamicComponents.value[componentNameKey[0]].path;
  // let path = "CustomInput/Index";
  let asyncComp = defineAsyncComponent(() =>
    import(`@/components/common/DinamicForm/Widgets/${path}.vue`)
  );
  // switch (type) {
  //   case "input":
  //     name = CustomInput;
  //     break;
  //   case "select":
  //     name = CustomSelect;
  //     break;
  //   case "textarea":
  //     name = CustomInput;
  //     break;
  //   case "button":
  //     name = Button;
  //     break;
  //   default:
  //     break;
  // }
  return asyncComp;
}

function handleFormWidgetNotify(params) {
  emits("notify", params);
}
// 获取表单组件
// function getDynamicFormWidgets(){
//     let result = {}
//     // webpack动态引入法
//     const widgetFileMapObj = require.context('./Widgets', true, /index\.js/)
//     widgetFileMapObj.keys()

//     // vite 动态引入法
//     // const widgetFileMapObj = import.meta.glob('./widgets/**/index.js')
//     // Object.keys(widgetFileMapObj)
//     widgetFileMapObj.keys().forEach(filePath=>{
//       var match = filePath.match(/\/([^/]+)\/[^/]*$/);
//       const key = match ? match[1] : '';
//       if(key !== '-widgets'){
//         result[key] = defineAsyncComponent(() => import(`@/components/common/DinamicForm/Widgets//${key}/${key}.vue`))
//       }
//     })
//     return result
// }

// onMounted(()=>{
//   getDynamicFormWidgets()
// })
</script>

<style lang="less" scoped>
.DinamicFormItem {
  :deep(.el-form-item) {
    .el-form-item__content {
      margin-left: 0px !important;
      flex-wrap: nowrap !important;
      .star {
        margin-right: 5px;
        color: #f56c6c;
      }
    }
  }
}
</style>
